package com.smartfast4j.manager.modules.schedule.bean;

import com.alibaba.fastjson.JSON;
import com.smartfast4j.common.util.IpUtil;
import com.smartfast4j.common.util.SpringContextUtils;
import com.smartfast4j.manager.modules.schedule.ScheduleRunnable;
import com.smartfast4j.manager.modules.schedule.service.ScheduleJobLogService;
import com.smartfast4j.pojo.schedule.ScheduleJob;
import com.smartfast4j.pojo.schedule.ScheduleJobLog;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 定时任务Bean
 */
@DisallowConcurrentExecution//@DisallowConcurrentExecution注解保证任务的串行
public class ScheduleJobBean extends QuartzJobBean {

    /**
     * 任务调度参数key
     */
    private static final String JOB_PARAM_KEY = "JOB_PARAM_KEY";
    private Logger logger = LoggerFactory.getLogger(getClass());
    private ExecutorService service = Executors.newSingleThreadExecutor();

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        String jsonJob = context.getMergedJobDataMap().getString(JOB_PARAM_KEY);
        ScheduleJob scheduleJob = JSON.parseObject(jsonJob, ScheduleJob.class);
        //获取scheduleJobLogService
        ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtils.getBean(ScheduleJobLogService.class);
        //保存执行记录到数据库
        ScheduleJobLog log = new ScheduleJobLog();
        log.setJobId(scheduleJob.getId());
        log.setJobName(scheduleJob.getJobName());
        log.setBeanName(scheduleJob.getBeanName());
        log.setMethodName(scheduleJob.getMethodName());
        log.setParams(scheduleJob.getParams());
        log.setCreateTime(new Date());
        log.setServerIp(IpUtil.getLocalIP());//获取执行定时任务的服务器的IP地址
        //任务开始时间
        long startTime = System.currentTimeMillis();
        try {
            //执行任务
            logger.info("任务准备执行，任务ID：" + scheduleJob.getId());
            ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(), scheduleJob.getMethodName(), scheduleJob.getParams());
            Future<?> future = service.submit(task);
            future.get();
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes((int)times);
            //任务状态    0：成功    1：失败
            log.setStatus(0);
            logger.info("任务执行完毕，任务ID：" + scheduleJob.getId() + "  总共耗时：" + times + "毫秒");
        } catch (Exception e) {
            logger.error("任务执行失败，任务ID：" + scheduleJob.getId(), e);
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes((int)times);
            //任务状态    0：成功    1：失败
            log.setStatus(1);
            log.setError(StringUtils.substring(e.toString(), 0, 2000));
            //发送预警邮件到指定的邮箱
            /*MsgPubService msgPubService = (MsgPubService) SpringContextUtils.getBean(MsgPubService.class);
            if(StringUtils.isNotEmpty(scheduleJob.getAlarmEmail())){
                String[] emailArr = scheduleJob.getAlarmEmail().split(",");
                for(String email:emailArr){
                    EmailMsgVo emailMsgVo = new EmailMsgVo();
                    emailMsgVo.setTo(email);
                    emailMsgVo.setSubject(scheduleJob.getJobName()+"任务执行出错通知");
                    emailMsgVo.setContent(scheduleJob.getJobName()+"任务执行出错，错误信息："+e.getMessage());
                    emailMsgVo.setEmailType(Constants.EMAIL_TYPE.SIMPLE_MAIL);
                    msgPubService.sendEmail(emailMsgVo);//发送邮件
                }
            }*/
        }finally {
            scheduleJobLogService.insertSelective(log);
        }
    }
}
